"""
@Author  : 康帅
@Time    : 2021/1/28 10:00
@Function: 导出xls文件工具，在开发中可将此功能加到接口中
"""
import xlwt

from io import BytesIO
from django.http import HttpResponse


def down_load_logger_tools(header, data_list):
    """
    header = []
    data_list = [[], []]
    """
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment;filename=logging.xls'
    wb = xlwt.Workbook(encoding='utf-8')
    # sheet名
    sheet = wb.add_sheet('操作日志记录表')
    pattern = xlwt.Pattern()
    pattern.pattern = xlwt.Pattern.SOLID_PATTERN
    pattern.pattern_fore_colour = 5
    style = xlwt.XFStyle()
    style.pattern = pattern

    # 导出excel表头
    if header:
        for number, value in enumerate(header):
            sheet.write(0, number, value, style)
    else:
        return HttpResponse('header为空，导出xls文件失败')

    # 导出excel数据
    if data_list:
        _excel_row = 1
        for k, v in enumerate(data_list):
            for i, j in enumerate(v):
                # 行　列　值
                sheet.write(_excel_row, i, j)
            _excel_row += 1
        # 写出到IO
        output = BytesIO()
        wb.save(output)
        # 重新定位到开始
        output.seek(0)
        response.write(output.getvalue())
        return response
    else:
        return HttpResponse('导出xls文件失败')
